<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\model\GoodsTag;
use app\common\model\Hospital;
use app\common\model\order\Order;
use app\common\model\order\OrderItem;
use think\Db;
use think\Model;

/**
 * 用户预约
 *
 * @icon fa fa-circle-o
 */
class Appoints extends Backend
{

    /**
     * Appoints模型对象
     * @var \app\common\model\user\Appoints
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\user\Appoints;
        $this->view->assign("isSendList", $this->model->getIsSendList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','hospital','cards','info','business'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname','mobile','avatar']);
				$row->getRelation('hospital')->visible(['hospital_name']);
                $row->getRelation('business')->visible(['business_name']);
				$row->getRelation('cards')->visible(['rights_title','rights_nums','can_uses','used_nums']);
				$row->getRelation('info')->visible(['medical_username','medical_gender','medical_cardno']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail($ids)
    {
        if ($this->request->isPost()) {
            $param = input('');
            Db::startTrans();

            $id = $ids;
            $row = $this->model->where(['id'=>$id])->find();

            $before_checkinfo = input('before_checkinfo');
            $checkinfo = input('checkinfo');
            $org = [];
            $checkinfoList = $this->model->checkinfoList;

            $params = input("row/a");

            //   ['待付款','待预约','已完成','全部退款','已取消'];



            if(isset($checkinfo)){
                if ($before_checkinfo != $checkinfo) {

                    $org = [
                        '状态由' . $checkinfoList[$before_checkinfo] . '改成' . $checkinfoList[$checkinfo],
                    ];

                }
            }else{
                $checkinfo=$before_checkinfo;
            }
            if($row['status']!=0&&$checkinfo!=$before_checkinfo)
            {
                $this->error('该预约订单不可以操作');
            }

            //  ['待付款','待预约','已完成','全部退款','已取消'];
            switch ($checkinfo) {

                case 1:
                    //待预约
                     if($row['status']==0){
                         $row['status']=1;
                         $row['auth_time']=time();
                         $config = get_addon_config('alisms');
                         $template='SMS_463215561';
                         $sign = $config['sign'];
                         $mobile=$row['appoint_mobile'];
                         $hospital=(new Hospital())->where(['id'=>$row['hisptial_id']])->find();
                         $param=['name'=>$row['username'],'date'=>$row['appoint_date'],
                             'hosp'=>$hospital?$hospital['hospital_name']:$row['hisptials_name']];
                         $alisms = new \addons\alisms\library\Alisms();
                         $ret = $alisms->mobile($mobile)
                             ->template($template)
                             ->sign($sign)
                             ->param($param)
                             ->send();
                         if ($ret) {
                             $row['is_success']=1;

                         } else {
                             $row['is_success']=1;
                         }
                     }

                    break;
                case 2:
                    //已完成
                    if($row['status']==0) {
                        $row['status'] = -1;
                        $row['cancel_time']=time();

                        $card = (new \app\common\model\UserCards())->where(['id'=>$row['card_id']])->find();
                        if($card['can_uses']==0){
                            (new \app\common\model\UserCards())->where(['id'=>$row['card_id']])->update(['status'=>1]);
                            Order::where(['id'=>$row['order_id']])->update(['status'=>1,'order_status'=>1]);
                        }
                        (new \app\common\model\UserCards())->where(['id'=>$row['card_id']])->setInc('can_uses');
                        (new \app\common\model\UserCards())->where(['id'=>$row['card_id']])->setDec('used_nums');
                        Order::where(['id'=>$row['order_id']])->setDec('canuse_appoints');
                        Order::where(['id'=>$row['order_id']])->setInc('used_appoints');
                        OrderItem::where(['id'=>$row['order_item_id']])->setInc('canuse_num');
                        OrderItem::where(['id'=>$row['order_item_id']])->setDec('used_num');
                        GoodsTag::where(['id'=>$row['tag_id']])->setDec('appoints');
                    }

                    break;


            }








            if (!empty($org)) {
                $this->modify_log($org, $row->id);
            }



            $res=$row->save();

            if($res){

                Db::commit();
                $this->success('');
            }else{
                Db::rollback();
            }






            $this->success();
        }

        $param = $this->request->param();

        $row = $this->model->with(['user'])->where('appoints.id', $param['ids'])->find();
        $hospital=(new Hospital())->where(['id'=>$row['hisptial_id']])->find();
        if($hospital){
           $hospital['address_text']= $hospital['province'].$hospital['city'].$hospital['area'].$hospital['address'];
        }
        $row['hospital']=$hospital;

        $row['log']=\db('appoints_log')->where(['order_id'=>$param['ids']])->select();
        $row->checkinfo =$this->getCheckinfo($row);


        $this->assign('checkinfoList', $this->model->checkinfoList);
        $this->view->assign('vo', $row);

        return $this->view->fetch();
    }
    public function getCheckinfo($row)
    {
        //     public $checkinfoList = ['待付款','待预约','已完成','全部退款','已取消'];
        $checkinfo=0;
        if($row['status']==1){
            $checkinfo=1;
        }else if($row['status']==-1){
            $checkinfo=2;
        }
        return $checkinfo;
    }
    //修改日志记录
    public function modify_log($row,$order_id,$type='order'){

        $data = [
            'order_id'      =>  $order_id,
            'mod_content'   =>  implode('、',$row),
            'admin_id'      =>  session('admin.id'),
            'type'          =>  $type,
            'createtime'    =>  time(),
            'updatetime'    =>  time(),
        ];
        db('appoints_log')->insert($data);

    }
}
